package com.shop.seckill.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.domain.Seckill;
import com.shop.domain.SeckillProduct;
import com.shop.seckill.mapper.SeckillMapper;
import com.shop.seckill.mapper.SeckillProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class TimeListener {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private SeckillProductMapper seckillProductMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    // 每天23点执行
    @Scheduled(cron =  "0 0 23 * * ?")
    //@Scheduled(cron = "0 0/2 * * * ?") //每两分钟执行一次
    public void timeListener(){
        //获取第二天的日期
        Date date = new Date(new Date().getTime() + 1000*60*60*24);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        String start = format + " 00:00:00";
        String end = format + " 23:59:59";
        LambdaQueryWrapper<Seckill> lqw = new LambdaQueryWrapper<>();
        lqw.ge(Seckill::getStartTime, start);
        lqw.le(Seckill::getEndTime, end);
        lqw.eq(Seckill::getIsDelete,0);
        // 查询秒杀活动
        List<Seckill> seckills = seckillMapper.selectList(lqw);
        if (seckills!=null&&seckills.size()>0) {
            for (Seckill seckill : seckills) {
                LambdaQueryWrapper<SeckillProduct> lqwp = new LambdaQueryWrapper<>();
                lqwp.eq(SeckillProduct::getSeckillId, seckill.getId());
                lqwp.eq(SeckillProduct::getIsDelete,0);
                // 查询秒杀商品
                List<SeckillProduct> seckillProducts = seckillProductMapper.selectList(lqwp);
                for (SeckillProduct seckillProduct : seckillProducts) {
                                                    // 年月日+时间场次   存秒杀商品
                    redisTemplate.boundHashOps(format+seckillProduct.getActivityTimes()).put(seckillProduct.getId(),seckillProduct);
                    //存库存                                                      为什么老师写的是getId()
                    redisTemplate.opsForValue().set("Inventory_"+seckillProduct.getProductId(),seckillProduct.getNum());
                    // 存秒杀的时间场次
                    redisTemplate.opsForSet().add(format,seckillProduct.getActivityTimes());
                }
            }
        }
    }
}
